import { baseUrl } from "./baseurl.js";

const install = (Vue) => {
	Vue.prototype.$u.http.setConfig({
		baseUrl: baseUrl,
		dataType: 'json',
		header: {
			'content-type': 'application/json',
			// token: uni.getStorageSync('token')
		},
	});
	Vue.prototype.$u.http.interceptor.request = async (config) => {
		let token = uni.getStorageSync('token');
		// if(config.header && config.header.needToken && token){
			config['header'].token = token;
		// }
		// delete config.data.needToken;
		// delete config['header'].justToken;
		return config;      
	}
	
	Vue.prototype.$u.http.interceptor.response = (res) => {
		if(res.code == 200) {
			return res;
		}else if(res.code === 401 && /登录/.test(res.message)){
			Vue.prototype.$u.toast(res.message);
		}else if(res.code === 403 && /权限/.test(res.message)){
			Vue.prototype.$u.toast(res.message);
			setTimeout(()=>{
				uni.reLaunch({
					url:'/pages/mine/index'
				})
			},800)
		}else if(res.code === 500 && /token/.test(res.message)){
			Vue.prototype.$u.toast('登录已失效，请重新登录');
			uni.removeStorageSync('token');
			setTimeout(()=>{
				uni.switchTab({
					url:'/pages/mine/index'
				})
			},800)
			return false;
		}else if(res.code === 500){
			Vue.prototype.$u.toast(res.message);
		}else {
			Vue.prototype.$u.toast(res.message);
			return false;
		}
	}
}

export default {
	install
}